package com.henghai.zhenxuan.ui.page.signin;


import android.os.Bundle;
import android.view.View;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.widget.AppCompatButton;

import com.henghai.zhenxuan.BR;
import com.henghai.zhenxuan.data.bean.LotteryBean;
import com.henghai.zhenxuan.data.bean.WinnerBean;
import com.henghai.zhenxuan.data.config.AppConfig;
import com.henghai.zhenxuan.domain.event.Messages;
import com.henghai.zhenxuan.domain.message.PageMessenger;
import com.henghai.zhenxuan.domain.request.GetPrizeCountRequester;
import com.henghai.zhenxuan.domain.request.PrizeDrawListRequester;
import com.henghai.zhenxuan.domain.request.PrizeDrawRuleRequester;
import com.henghai.zhenxuan.domain.request.PrizeResRequester;
import com.henghai.zhenxuan.domain.request.UserInfoRequester;
import com.henghai.zhenxuan.domain.request.WinningRequester;
import com.henghai.zhenxuan.ui.page.adapter.WinnerListAdapter;
import com.henghai.zhenxuan.ui.view.nine.LotteryView;
import com.henghai.zhenxuan.utils.MainHandler;
import com.henghai.zhenxuan.R;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;
import com.kongzue.dialogx.dialogs.MessageDialog;
import com.kongzue.dialogx.dialogs.TipDialog;
import com.kongzue.dialogx.dialogs.WaitDialog;
import com.kongzue.dialogx.interfaces.BottomDialogSlideEventLifecycleCallback;
import com.kongzue.dialogx.interfaces.OnBindView;
import com.kunminx.architecture.ui.page.BaseFragment;
import com.kunminx.architecture.ui.page.DataBindingConfig;
import com.kunminx.architecture.ui.page.StateHolder;
import com.kunminx.architecture.ui.state.State;

import java.util.ArrayList;
import java.util.List;

public class LotteryFragment extends BaseFragment {
    public static final String KEY_ID = "prizeId";
    public static final String KEY_TYPE = "prizeDrawType";


    private LotteryStates mStates;
    private PrizeDrawListRequester mPrizeDrawListRequester;
    private PrizeResRequester mPrizeResRequester;
    private LotteryView mLotteryView;
    private String prizeRes;
    private UserInfoRequester mUserInfoRequester;
    private PageMessenger mMessenger;
    private PrizeDrawRuleRequester mPrizeDrawRuleRequester;
    private WinnerListAdapter mAdapter;
    private WinningRequester mWinningRequester;
    private GetPrizeCountRequester mGetPrizeCountRequester;
    private String prizeId;


    @Override
    protected void initViewModel() {
        mStates = getFragmentScopeViewModel(LotteryStates.class);
        mPrizeResRequester = getFragmentScopeViewModel(PrizeResRequester.class);
        mPrizeDrawListRequester = getFragmentScopeViewModel(PrizeDrawListRequester.class);
        mMessenger = getApplicationScopeViewModel(PageMessenger.class);
        mUserInfoRequester = getFragmentScopeViewModel(UserInfoRequester.class);


        mPrizeDrawRuleRequester = getFragmentScopeViewModel(PrizeDrawRuleRequester.class);
        mWinningRequester = getFragmentScopeViewModel(WinningRequester.class);
        mGetPrizeCountRequester = getFragmentScopeViewModel(GetPrizeCountRequester.class);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        Bundle bundle = getArguments();
        String prizeType = bundle != null ? bundle.getString(KEY_TYPE, "") : "";
        prizeId = bundle != null ? bundle.getString(KEY_ID, "") : "";

//        if (prizeId == null || prizeId.isEmpty()) {
//            TipDialog.show("");
//            nav().navigateUp();
//            return;
//        }
        mStates.prizeType.set(prizeType);

        mGetPrizeCountRequester.getResult().observe(this, dataResult -> {
            if (!dataResult.getResponseStatus().isSuccess()) {
                return;
            }
            AppConfig.INSTANCE.setPrizeCount(dataResult.getResult().getMsg());
            mStates.prizeCount.set(AppConfig.INSTANCE.getPrizeCount());
        });

        mWinningRequester.getResult().observe(this, dataResult -> {
            if (!dataResult.getResponseStatus().isSuccess()) {
                return;
            }
            mStates.winnerList.set(dataResult.getResult().getData().getRows());
        });
        mWinningRequester.request(this);
        mPrizeDrawRuleRequester.getResult().observe(this, dataResult -> {
            if (!dataResult.getResponseStatus().isSuccess()) {
                return;
            }
            mStates.expendPoints.set(dataResult.getResult().getData().getExpendPoints() + "积分一次");
        });
        mPrizeDrawRuleRequester.request(this, prizeId);


        mUserInfoRequester.getTokenResult().observe(this, dataResult -> {
            if (!dataResult.getResponseStatus().isSuccess()) {
                return;
            }
            AppConfig.INSTANCE.getMConfigs().user().set(dataResult.getResult().getData());
            mStates.userPoints.set((int) Double.parseDouble(AppConfig.INSTANCE.getMConfigs().user().get().getUserPoints()) + "积分");
            mMessenger.input(new Messages(Messages.EVENT_USERINFO_SUCCESS));
        });
        mStates.userPoints.set((int) Double.parseDouble(AppConfig.INSTANCE.getMConfigs().user().get().getUserPoints()) + "积分");

        mPrizeResRequester.getResult().observe(this, httpBeanDataResult -> {
            WaitDialog.dismiss();
            mUserInfoRequester.request(this);
            mGetPrizeCountRequester.request(getViewLifecycleOwner());
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                if (!httpBeanDataResult.getResponseStatus().getResponseCode().equals("谢谢惠顾")) {
                    TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                } else {
                    mLotteryView.startLottery(7);
                }
                return;
            }
            prizeRes = httpBeanDataResult.getResult().getData().getProductName();
            for (int i = 0; i < mStates.lotteryList.get().size(); i++) {
                if (mStates.lotteryList.get().get(i).getProductName().equals(prizeRes)) {
                    mLotteryView.startLottery(i);
                    break;
                }
            }
        });
        mPrizeDrawListRequester.getTokenResult().observe(this, httpBeanDataResult -> {
            if (!httpBeanDataResult.getResponseStatus().isSuccess()) {
                TipDialog.show(httpBeanDataResult.getResponseStatus().getResponseCode(), WaitDialog.TYPE.ERROR);
                return;
            }
            if (!httpBeanDataResult.getResult().getData().isEmpty()) {
                LotteryBean lotteryBean = new LotteryBean();
                lotteryBean.setUrl(com.henghai.zhenxuan.R.mipmap.ic_launcher);
                lotteryBean.setProductName("");
                httpBeanDataResult.getResult().getData().add(lotteryBean);
                int offset = 9 - httpBeanDataResult.getResult().getData().size();
                for (int i = 0; i < offset; i++) {
                    lotteryBean.setProductName("谢谢惠顾");
                    httpBeanDataResult.getResult().getData().add(lotteryBean);
                }
                mStates.lotteryList.set(httpBeanDataResult.getResult().getData());
                mGetPrizeCountRequester.request(this);
            }
        });
        mPrizeDrawListRequester.request(this, prizeId);


    }

    @Override
    protected DataBindingConfig getDataBindingConfig() {

        mAdapter = new WinnerListAdapter(getContext());
        return new DataBindingConfig(R.layout.fragment_lottery, BR.vm, mStates)
                .addBindingParam(BR.listener, new ListenerHandler()).addBindingParam(BR.adapter, mAdapter)
                .addBindingParam(BR.lotteryListener, new LotteryHandler()).addBindingParam(BR.click, new LotteryFragment.ClickProxy());
    }

    public class ListenerHandler implements OnTitleBarListener {
        @Override
        public void onLeftClick(TitleBar titleBar) {
            OnTitleBarListener.super.onLeftClick(titleBar);
            nav().navigateUp();
        }

        @Override
        public void onRightClick(TitleBar titleBar) {
            OnTitleBarListener.super.onRightClick(titleBar);
        }
    }

    public int dip2px(float dpValue) {
        float scale = this.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5F);
    }

    public class LotteryHandler implements LotteryView.LotteryListener {
        @Override
        public void onEnd() {
            if (prizeRes == null || prizeRes.isEmpty()) {
                MessageDialog.show("", "")
                        .setDialogLifecycleCallback(new BottomDialogSlideEventLifecycleCallback<MessageDialog>() {
                            @Override
                            public void onShow(MessageDialog dialog) {
                                super.onShow(dialog);
                                dialog.getDialogImpl().txtDialogTip.setPadding(0, dip2px(20), 0, 0);
                            }
                        })
                        .setCustomView(new OnBindView<MessageDialog>(R.layout.layout_custom_view) {
                            @Override
                            public void onBind(MessageDialog dialog, View v) {
                                AppCompatButton continue_lottery = v.findViewById(R.id.continue_lottery);
                                continue_lottery.setOnClickListener(v1 -> {
                                    mPrizeResRequester.request(getViewLifecycleOwner(), prizeId);
                                    dialog.dismiss();
                                });
                                View lottery_not_close = v.findViewById(R.id.lottery_not_close);
                                lottery_not_close.setOnClickListener(v12 -> dialog.dismiss());
                            }
                        });
                return;
            }
            MessageDialog.show("中奖了", "恭喜您抽中" + prizeRes).setOkButton("确定");

            MainHandler.INSTANCE.postDelay(3000, () -> mLotteryView.resetLottery());
        }

        @Override
        public void onClickLottery(@NonNull LotteryView lotteryView) {
            mLotteryView = lotteryView;
            prizeRes = "";
            WaitDialog.show("请稍后");
            mPrizeResRequester.request(getViewLifecycleOwner(), prizeId);

        }
    }

    public class ClickProxy {
        public void prize() {
            nav().navigate(R.id.action_lotteryFragment_to_PrizeFragment);
        }
    }

    public static class LotteryStates extends StateHolder {
        public final State<List<WinnerBean.RowsBean>> winnerList = new State<>(new ArrayList<>());
        public final State<String> myPrize = new State<>("我的奖品");
        public final State<String> prizeCount = new State<>("");
        public final State<String> userPoints = new State<>("");
        public final State<String> expendPoints = new State<>("10积分一次");
        public final State<String> prizeType = new State<>("");


        public final State<ArrayList<LotteryBean>> lotteryList = new State<>(new ArrayList<>());
    }
}
